import os
import json

dirname, filename = os.path.split(os.path.abspath(__file__)) 
# os.path.realpath(__file__)

WEBSPIDER_CONFIG_PATH = os.path.join(dirname, 'config.json')

def listConfig():
    fd = open(WEBSPIDER_CONFIG_PATH, mode="r", encoding="utf-8")
    text = fd.read()
    fd.close()

    return json.loads(text) if len(text) else []

def addConfig(webspiderConfig):
    fd = open(WEBSPIDER_CONFIG_PATH, mode="r", encoding="utf-8")
    text = fd.read()
    fd.close()

    configs = json.loads(text) if len(text) else []
    configs.append(webspiderConfig)

    fd = open(WEBSPIDER_CONFIG_PATH, mode="w", encoding="utf-8")
    fd.write(json.dumps(configs, ensure_ascii=False, indent=3))
    fd.close()

def deleteConfig(index):
    if index < 0:
        return False

    fd = open(WEBSPIDER_CONFIG_PATH, mode="r", encoding="utf-8")
    text = fd.read()
    fd.close()

    configs = json.loads(text) if len(text) else []

    if index >= len(configs):
        return False

    configs.pop(index)

    fd = open(WEBSPIDER_CONFIG_PATH, mode="w", encoding="utf-8")
    fd.write(json.dumps(configs, ensure_ascii=False, indent=3))
    fd.close()

def getConfig(index):
    if index < 0:
        return False

    fd = open(WEBSPIDER_CONFIG_PATH, mode="r", encoding="utf-8")
    text = fd.read()
    fd.close()

    configs = json.loads(text) if len(text) else []

    if index >= len(configs):
        return False

    return configs[index]

def updateConfig(index, nconfig):
    if index < 0:
        return False

    fd = open(WEBSPIDER_CONFIG_PATH, mode="r", encoding="utf-8")
    text = fd.read()
    fd.close()

    configs = json.loads(text) if len(text) else []

    if index >= len(configs):
        return False

    configs[index] = nconfig

    fd = open(WEBSPIDER_CONFIG_PATH, mode="w", encoding="utf-8")
    fd.write(json.dumps(configs, ensure_ascii=False, indent=3))
    fd.close()

'''
for item in listConfig():
    print(item)
'''

'''
addConfig({'a': 1})
addConfig({'a': 2})
addConfig({'a': 3})
'''

# deleteConfig(len(listConfig()) - 2)